package com.one.common.view.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.text.method.NumberKeyListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.one.common.R;
import com.one.common.utils.ScreenUtils;
import com.one.common.utils.StringUtils;
import com.one.common.view.pagestate.refreshlayout.utils.DensityUtil;


/**
 * creator: zhulunjun
 * time:    2018/7/9
 * describe: 输入控件组合
 */

public class InputLayout extends LinearLayout implements View.OnTouchListener {

    private TextView tvName, tvCenter, tvRight, tvRed, tvname_right_red, tvLeft;
    private ClearEditView clearEditView;
    private ImageView ivRight, ivLeft, ivRight2;
    private boolean isEdit;
    private LinearLayout llInput;
    private boolean hasLine;
    private boolean hasRedTag;
    private View line;
    private OnClickListener listener;

    public InputLayout(Context context) {
        super(context, null);
    }

    public InputLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if (attrs == null) {
            return;
        }
        LayoutInflater.from(context).inflate(R.layout.layout_input, this);
        TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.InputLayout);
        String name = ta.getString(R.styleable.InputLayout_name);
        int nameRes = ta.getResourceId(R.styleable.InputLayout_name, -1);
        String hint = ta.getString(R.styleable.InputLayout_hint);
        int hintRes = ta.getResourceId(R.styleable.InputLayout_hint, -1);
        String textRight = ta.getString(R.styleable.InputLayout_text_right);
        String textLeft = ta.getString(R.styleable.InputLayout_text_left);
        int textRightRes = ta.getResourceId(R.styleable.InputLayout_text_right, -1);
        int imgRight = ta.getResourceId(R.styleable.InputLayout_img_right, -1);
        int imgLeft = ta.getResourceId(R.styleable.InputLayout_img_left, -1);
        int nameColor = ta.getResourceId(R.styleable.InputLayout_name_color, -1);
        int sizeText = ta.getResourceId(R.styleable.InputLayout_name_size, -1);
        int maxLength = ta.getResourceId(R.styleable.InputLayout_il_max_length, -1);
        isEdit = ta.getBoolean(R.styleable.InputLayout_is_input, true);
        hasLine = ta.getBoolean(R.styleable.InputLayout_has_line, true);
        hasRedTag = ta.getBoolean(R.styleable.InputLayout_has_red_tag, false);
        boolean isRequest = ta.getBoolean(R.styleable.InputLayout_is_request, false);
        int gravity = ta.getInt(R.styleable.InputLayout_text_gravity, 1);
        int nameWidth = ta.getInt(R.styleable.InputLayout_il_name_width, 0);
        initView();
        setName(name);
        setName(nameRes);
        setHint(hint);
        setHint(hintRes);
        setTextRight(textRight);
        setTextLeft(textLeft);
        setTextRight(textRightRes);
        setRightImg(imgRight);
        setLeftImg(imgLeft);
        setNameColor(nameColor);
        setName16Size(sizeText);
        isEdite(isEdit);
        setLineVisibility(hasLine);
        setTextGravity(gravity);
        setMaxEditLength(maxLength);
        setNameWidth(nameWidth);
        setRequest(isRequest);

        ta.recycle();

    }

    private void initView() {
        tvName = (TextView) findViewById(R.id.tv_name);
        tvLeft = (TextView) findViewById(R.id.tv_left);
        tvRight = (TextView) findViewById(R.id.tv_right);
        tvCenter = (TextView) findViewById(R.id.tv_center);
        ivRight = (ImageView) findViewById(R.id.iv_right);
        ivRight2 = (ImageView) findViewById(R.id.iv_right_2);
        ivLeft = (ImageView) findViewById(R.id.iv_left);
        clearEditView = findViewById(R.id.et_text);
        llInput = findViewById(R.id.ll_input);
        line = findViewById(R.id.v_line);
        tvRed = findViewById(R.id.tv_red);
        tvname_right_red = findViewById(R.id.tvname_right_red);

        llInput.setOnClickListener(v -> {
            if (listener != null) {
                listener.onClick(InputLayout.this);
            }
        });

        clearEditView.setOnTouchListener(this);

//        if (hasRedTag){
//            tvRed.setVisibility(VISIBLE);
//        }else {
//            tvRed.setVisibility(GONE);
//        }


//        clearEditView.setFilters(EmojiInputHandle.getEmojiInputFiler());
    }

    public void setRightRedShow(){
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, 16, 0, 16);
        tvName.setLayoutParams(layoutParams);
        tvCenter.setGravity(Gravity.RIGHT);
        tvname_right_red.setVisibility(VISIBLE);

    }

    public void setRequest(boolean isRequest) {
        if (isRequest) {
            tvRed.setVisibility(VISIBLE);
        } else {
            tvRed.setVisibility(GONE);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        llInput.setEnabled(enabled);
    }

    /**
     * 设置name的宽度
     */
    public void setNameWidth(int width) {
        if (width == 0) return;
        LayoutParams layoutParams = (LayoutParams) tvName.getLayoutParams();
        layoutParams.width = ScreenUtils.dp2px(getContext(), width);
        tvName.setLayoutParams(layoutParams);
    }

    public void setTextGravity(int gravity) {
        if (gravity == 0) {
            tvCenter.setGravity(Gravity.CENTER);
            clearEditView.setGravity(Gravity.CENTER);
        } else if (gravity == 1) {
            tvCenter.setGravity(Gravity.START);
            clearEditView.setGravity(Gravity.START);
        } else if (gravity == 2) {
            tvCenter.setGravity(Gravity.END);
            clearEditView.setGravity(Gravity.END);
        }
    }

    public void setNameColor(int color) {
        if (color != -1) {
            tvName.setTextColor(getResources().getColor(color));
        }
    }

    public void setName16Size(int size){
        if (size != -1){
            tvName.getPaint().setTextSize(getResources().getDimension(size));
        }
    }

    public TextView getTvName() {
        return tvName;
    }

    public void setName(String name) {
        if (StringUtils.isNotBlank(name)) {
            tvName.setText(name);
        }
    }

    public void setName(int nameRes) {
        if (nameRes != -1) {
            tvName.setText(nameRes);
        }
    }



    public void setTvLeft(int nameRes) {
        if (nameRes != -1) {
            tvName.setText(nameRes);
        }
    }

    public void setNameMaxLines(int lines){
        tvName.setMaxLines(lines);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0,0,0,0);
        tvName.setLayoutParams(layoutParams);
    }

    public void setRightImg(int res) {
        if (res != -1) {
            ivRight.setVisibility(VISIBLE);
            ivRight.setImageResource(res);
        } else {
            ivRight.setVisibility(GONE);
        }
    }

    public void setLeftImg(int res) {
        if (res != -1) {
            ivLeft.setVisibility(VISIBLE);
            ivLeft.setImageResource(res);
        } else {
            ivLeft.setVisibility(GONE);
        }
    }

    public void setTextRight(String text) {
        if (StringUtils.isNotBlank(text)) {
            tvRight.setVisibility(VISIBLE);
            tvRight.setText(text);
        }
    }

    public void setTextLeft(String text) {
        if (StringUtils.isNotBlank(text)) {
            tvLeft.setVisibility(VISIBLE);
            tvLeft.setText(text);
        }
    }

    public void setTextRight(int text) {
        if (text != -1) {
            tvRight.setVisibility(VISIBLE);
            tvRight.setText(text);
        }
    }

    public void setHint(String hint) {
        if (StringUtils.isNotBlank(hint)) {
            if (isEdit) {
                clearEditView.setHint(hint);
            } else {
                tvCenter.setHint(hint);
            }
        }
    }

    public void setTextCenter(String textCenter) {
        if (clearEditView.isShown()) {
            clearEditView.setVisibility(GONE);
        }
        tvCenter.setVisibility(VISIBLE);
        tvCenter.setText(textCenter);
    }

    public void setTvCenterColor(){
        tvCenter.setTextColor(getResources().getColor(R.color.root_red));
    }

    public void setText(String text) {
        if (isEdit) {
            clearEditView.setText(text);
        } else {
            setTextCenter(text);
        }
    }

    public void setHint(int hintRes) {

        if (hintRes != -1) {
            if (isEdit) {
                clearEditView.setHint(hintRes);
            } else {
                tvCenter.setHint(hintRes);
            }
        }
    }

    public String getText() {
        if (isEdit) {
            return clearEditView.getText().toString();
        } else {
            return tvCenter.getText().toString();
        }
    }

    public void setFouceEnd() {
        clearEditView.requestFocus();
        clearEditView.setSelection(getText().length());

    }

    public void setEnableEdiitView(boolean canDone){
        clearEditView.setEnabled(canDone);
    }

    public TextView getTvCenter() {
        return tvCenter;
    }

    public ClearEditView getEditView() {
        return clearEditView;
    }


    /***
     *  设置为： 编辑框 仅支持数字
     */
    public void setEditViewNumber(){
        clearEditView.setKeyListener(new NumberKeyListener() {
            @Override
            protected char[] getAcceptedChars() {
                return new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'};
            }

            @Override
            public int getInputType() {
                return InputType.TYPE_CLASS_TEXT;
            }
        });

        clearEditView.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);
        clearEditView.setKeyListener(new DigitsKeyListener(false, true));
    }

    public void setTextChange(ClearEditView.TextChangeListener listener) {
        clearEditView.setTextChangeListener(listener);
    }

    public void isEdite(boolean isEdit) {
        this.isEdit = isEdit;
        if (isEdit) {
            clearEditView.setVisibility(VISIBLE);
            tvCenter.setVisibility(GONE);
        } else {
            clearEditView.setVisibility(GONE);
            tvCenter.setVisibility(VISIBLE);
        }
    }

    public void setLineVisibility(boolean hasLine) {
        if (hasLine) {
            line.setVisibility(VISIBLE);
        } else {
            line.setVisibility(GONE);
        }
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener l) {
        listener = l;

    }

    public TextView getTvRight() {
        return tvRight;
    }

    /**
     * 设置最大输入长度
     *
     * @param max
     */
    public void setMaxEditLength(int max) {
        if (max > 0) {
            clearEditView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max)});
        }

    }

    /**
     * 设置字体左边的图标
     */
    public void setTvRightDrawableLeft(int imgRes, int padding) {
        Drawable drawableLeft = getResources().getDrawable(imgRes);
        tvRight.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
        tvRight.setCompoundDrawablePadding(DensityUtil.dp2px(getContext(), padding));
    }

    /**
     * 设置字体左边的图标
     */
    public void setTvDrawableLeft(int imgRes, int padding) {
        Drawable drawableLeft = getResources().getDrawable(imgRes);
        tvCenter.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
        tvCenter.setCompoundDrawablePadding(DensityUtil.dp2px(getContext(), padding));
    }

    /***
     *  设置字体左边的图标 by  rgb
     * @param color
     * @param padding
     */
    public void setTvDrawableLeftByColor(String color, int padding) {
        if (StringUtils.isEmpty(color)){
            color = "#FFFFFF";
        }


        int roundRadius = 12; // 12dp 圆角半径
        int strokeColor = Color.parseColor(color);//边框颜色
        int fillColor = Color.parseColor(color);//内部填充颜色
        GradientDrawable gd = new GradientDrawable();//创建drawable
        gd.setColor(fillColor);
        gd.setStroke(1, strokeColor);
//        gd.setCornerRadius(roundRadius);
        gd.setSize(40, 40);
        gd.setShape(GradientDrawable.OVAL);

        tvCenter.setCompoundDrawablesWithIntrinsicBounds(gd, null, null, null);
        tvCenter.setCompoundDrawablePadding(DensityUtil.dp2px(getContext(), padding));
    }

    public String getRightText() {
        return tvRight.getText().toString();
    }


    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
        if ((view.getId() == R.id.et_text && canVerticalScroll(clearEditView))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return super.onTouchEvent(motionEvent);
    }

    public ImageView getIvRight() {
        return ivRight;
    }

    public ImageView getIvRight2() {
        return ivRight2;
    }
}
